<template>
  <view v-if="items" class="switch-btn">
    <view
      class="switch-btn-bg"
      :style="{'transform': `translateX(${currentIndex * 82}rpx)`}"
    ></view>
    <text
      :class="{ active: val[keyField] === item.id }"
      v-for="item in items"
      :key="item[keyField]"
      @tap="handleTapItem(item)"
    >{{ item[displayField] }}</text>
  </view>
</template>

<script>
import ValueMixin from '../mixin/value-mixin.js'
export default {
  name: 'SwitchBtn',
  mixins: [ValueMixin],
  props: {
    // 选项列表
    items: {
      required: true,
      type: Array,
      default () {
        return []
      }
    },
    // 选项id字段，默认为id
    keyField: {
      required: false,
      type: String,
      default: 'id'
    },
    // 选项显示字段，默认为text
    displayField: {
      required: false,
      type: String,
      default: 'text'
    }
  },
  computed: {
    currentIndex () {
      return this.items.findIndex(item => item[this.keyField] === this.val[this.keyField])
    }
  },
  methods: {
    handleTapItem (item) {
      this.val = item
      this.$emit('change', item)
    }
  }
}
</script>

<style lang="scss" scoped>
.switch-btn {
  position: relative;
  background-color: #f6f7f9;
  border: 2rpx solid #f6f7f9;
  border-radius: 500000rpx;
  overflow: hidden;
  & > text {
    position: relative;
    display: inline-block;
    width: 82rpx;
    height: 56rpx;
    line-height: 56rpx;
    text-align: center;
    font-size: 30rpx;
    z-index: 2;
    transition: color 0.3s ease-in-out;
    &.active {
      color: #ffffff;
    }
  }
  .switch-btn-bg {
    position: absolute;
    left: 0;
    top: 0;
    width: 82rpx;
    height: 56rpx;
    background: #43a047;
    border-radius: 500000rpx;
    overflow: hidden;
    z-index: 1;
    transition: transform 0.3s ease-in-out;
  }
}
</style>